/**
 * 处理OAuth请求事件的handler类，读取数据库判断是否已经存在openid，从而返回不同的result。
 * @author Hehong
 * 2015.3.31
 */

package com.Hehong;

import java.util.ArrayList;
import java.util.Iterator;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.disco.ServerFeaturesProvider;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

public class IQOAuthHandler extends IQHandler implements ServerFeaturesProvider {

	private static final Logger Log = LoggerFactory.getLogger(IQOAuthHandler.class);

    private static Element probeResult;

    private IQHandlerInfo info;

    /**
     * <p>Basic constructor does nothing.</p>
     */
    public IQOAuthHandler() {
        super("XMPP OAuth Handler");
        info = new IQHandlerInfo("query", "jabber:iq:oauth");
    }

    @Override
	public void initialize(XMPPServer server) {
        super.initialize(server);
        //System.out.println("进入OAUTh处理的handler类了！：initialize");
    }

    @Override
	public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
    	System.out.println("进入OAUTh处理的handler类了！：handleIQ");
        ClientSession session = sessionManager.getSession(packet.getFrom());
        IQ reply = null;
        // If no session was found then answer an error (if possible)
        if (session == null) {
            Log.error("Error during registration. Session not found in " +
                    sessionManager.getPreAuthenticatedKeys() +
                    " for key " +
                    packet.getFrom());
            // This error packet will probably won't make it through
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            return reply;
        }
        if (IQ.Type.get.equals(packet.getType())) {
        	Element iqElement = packet.getChildElement();
        	String openid;
        	String from;
        	openid = iqElement.elementText("openid");
        	from = iqElement.elementText("from");
        	System.out.println("获得了openid、from信息："+openid+from);
        	DbOAuthManager oAuthDbManager = new DbOAuthManager();
        	String OAuthResult = oAuthDbManager.getUserName(openid, from);
        	System.out.println("OAuthResult的值是："+OAuthResult);
        	
        	if (OAuthResult==null) {
//        		如果之前没有用该openid注册过，那么返回一条没有任何东西的result命令
        		reply = IQ.createResultIQ(packet);
			}
        	else{
        		String myusername = OAuthResult;
        		String mypassword = null;
            	try {
    				mypassword = AuthFactory.getPassword(OAuthResult);
    			} catch (UnsupportedOperationException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (UserNotFoundException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
            	//System.out.println("OAUth的密码是："+mypassword);
            	reply = IQ.createResultIQ(packet);
//            	由于客户端只能识别jabber:iq:register，所以query的xmlns值用jabber:iq:register。
            	probeResult = DocumentHelper.createElement(QName.get("query", "jabber:iq:register"));
            	probeResult.addElement("username");
            	probeResult.addElement("password");
            	probeResult.element("username").addText(myusername);
            	probeResult.element("password").addText(mypassword);
            	reply.setChildElement(probeResult.createCopy());
        	}
        }
        if (reply != null) {
            // why is this done here instead of letting the iq handler do it?
            session.process(reply);
        }
        return null;
    }

    @Override
	public IQHandlerInfo getInfo() {
        return info;
    }

    @Override
	public Iterator<String> getFeatures() {
        ArrayList<String> features = new ArrayList<String>();
        features.add("jabber:iq:oauth");
        return features.iterator();
    }
}
